<template>
  <div class="app-container">
    <!-- 功能选项卡 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="往来单位对比" name="comparison">
        <!-- 搜索区域 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="码上放心客户名称" prop="msfxCustomerName">
            <el-input v-model="queryParams.msfxCustomerName" placeholder="请输入码上放心客户名称" clearable style="width: 180px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="ERP客户名称" prop="erpCustomerName">
            <el-input v-model="queryParams.erpCustomerName" placeholder="请输入ERP客户名称" clearable style="width: 180px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="映射状态" prop="mappingStatus">
            <el-select v-model="queryParams.mappingStatus" placeholder="请选择映射状态" clearable style="width: 120px">
              <el-option label="全部" :value="null" />
              <el-option label="已映射" :value="true" />
              <el-option label="未映射" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 主要内容区域 -->
        <div class="comparison-container">
          <!-- 左侧：码上放心往来单位 -->
          <div class="left-panel">
            <div class="panel-header">
              <h3>码上放心往来单位</h3>
              <div class="panel-actions">
                <el-button type="primary" size="mini" icon="el-icon-refresh"
                  :loading="updateCustomerLoading" @click="handleUpdateCustomer"
                  v-hasPermi="['basic:customerComparison:list']">
                  {{ updateCustomerLoading ? '更新中...' : '更新往来单位' }}
                </el-button>
                <el-button type="success" size="mini"  @click="handleAutoMatchPreview">
                  自动匹配
                </el-button>
                <el-button type="primary" size="mini"
                  :disabled="msfxSelection.length !== 1 || erpSelection.length < 1" @click="handleCreateMapping">
                  创建映射
                </el-button>
                <el-button type="success" size="mini"
                  :disabled="msfxSelection.length !== 1 || erpSelection.length < 2" @click="handleBatchCreateMapping">
                  批量映射
                </el-button>
              </div>
            </div>
            <el-table v-loading="msfxLoading" :data="msfxCustomerList" border height="600px"
              @selection-change="handleMsfxSelectionChange" :row-class-name="getMsfxRowClassName">
             <el-table-column type="selection" width="55" align="center" />
             <el-table-column label="映射状态" align="center" width="120">
               <template slot-scope="scope">
                 <div v-if="scope.row.isMapped">
                   <el-tag type="success" size="mini">已映射</el-tag>
                   <span v-if="scope.row.mappingCount > 1" style="margin-left: 5px; font-size: 12px; color: #409EFF;">
                     ({{ scope.row.mappingCount }}个)
                   </span>
                 </div>
                 <el-tag v-else type="info" size="mini">未映射</el-tag>
               </template>
             </el-table-column>
             <el-table-column label="客户编号" align="center" prop="customerId" width="120"
               :show-overflow-tooltip="true" />
             <el-table-column label="客户名称" align="center" prop="customerName" min-width="180"
               :show-overflow-tooltip="true" />
             <el-table-column label="映射信息" align="center" width="220" :show-overflow-tooltip="true">
               <template slot-scope="scope">
                 <div v-if="scope.row.isMapped">
                   <div v-if="scope.row.mappingCount === 1">
                     {{ scope.row.mappedErpName || '映射信息异常' }}
                   </div>
                   <div v-else-if="scope.row.mappingCount > 1">
                     <el-popover placement="top" width="400" trigger="hover">
                       <div v-if="scope.row.mappingList && scope.row.mappingList.length > 0">
                         <div v-for="(mapping, index) in scope.row.mappingList" :key="index" style="margin-bottom: 5px;">
                           <el-tag size="mini" style="margin-right: 5px;">{{ index + 1 }}</el-tag>
                           {{ mapping.erpCustomerName || mapping.erpCustomerCode || '映射信息异常' }}
                         </div>
                       </div>
                       <div v-else style="color: #999;">
                         映射列表为空
                       </div>
                       <span slot="reference" style="color: #409EFF; cursor: pointer;">
                         {{ scope.row.mappedErpName || '多个映射关系' }}
                       </span>
                     </el-popover>
                   </div>
                   <div v-else>
                     {{ scope.row.mappedErpName || '映射信息异常' }}
                   </div>
                 </div>
                 <span v-else style="color: #999;">未映射</span>
               </template>
             </el-table-column>
             <el-table-column label="操作" align="center" width="100">
               <template slot-scope="scope">
                 <el-button v-if="scope.row.isMapped" size="mini" type="text" icon="el-icon-close"
                   @click="handleRemoveMsfxMapping(scope.row)"
                   v-hasPermi="['basic:customerComparison:remove']">解除映射</el-button>
               </template>
             </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                background
                layout="total, prev, pager, next, sizes, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="msfxQueryParams.pageNum"
                :page-size="msfxQueryParams.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="msfxTotal">
              </el-pagination>
            </div>
          </div>

          <!-- 右侧：ERP往来单位 -->
          <div class="right-panel">
            <div class="panel-header">
              <h3>ERP往来单位</h3>
            </div>
            <el-table v-loading="erpLoading" :data="erpCustomerList" border height="600"
              @selection-change="handleErpSelectionChange" :row-class-name="getErpRowClassName">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="映射状态" align="center" width="80">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.isMapped" type="success" size="mini">已映射</el-tag>
                  <el-tag v-else type="info" size="mini">未映射</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="单位编号" align="center" prop="danwbh" width="120" :show-overflow-tooltip="true" />
              <el-table-column label="单位名称" align="center" prop="dwmch" min-width="180" :show-overflow-tooltip="true" />
              <el-table-column label="映射信息" align="center" width="180" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span v-if="scope.row.isMapped">{{ scope.row.mappedMsfxName }}</span>
                  <span v-else style="color: #999;">未映射</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="100">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.isMapped" size="mini" type="text" icon="el-icon-close"
                    @click="handleRemoveErpMapping(scope.row)"
                    v-hasPermi="['basic:customerComparison:remove']">解除映射</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                background
                layout="total, prev, pager, next, sizes, jumper"
                @size-change="handleSizeChangeR"
                @current-change="handleCurrentChangeR"
                :current-page="erpQueryParams.pageNum"
                :page-size="erpQueryParams.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="erpTotal">
              </el-pagination>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 映射管理选项卡 -->
      <el-tab-pane label="映射管理" name="mapping">
        <div class="mapping-management">
          <!-- 映射关系搜索 -->
          <el-form :model="mappingQueryParams" ref="mappingQueryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="码上放心客户名称" prop="msfxCustomerName">
              <el-input v-model="mappingQueryParams.msfxCustomerName" placeholder="请输入码上放心客户名称" clearable
                style="width: 200px" @keyup.enter.native="handleMappingQuery" />
            </el-form-item>
            <el-form-item label="ERP客户名称" prop="erpCustomerName">
              <el-input v-model="mappingQueryParams.erpCustomerName" placeholder="请输入ERP客户名称" clearable
                style="width: 200px" @keyup.enter.native="handleMappingQuery" />
            </el-form-item>
            <el-form-item label="审核状态" prop="auditStatus">
              <el-select v-model="mappingQueryParams.auditStatus" placeholder="请选择审核状态" clearable style="width: 120px">
                <el-option label="待审核" :value="0" />
                <el-option label="已审核" :value="1" />
                <el-option label="已拒绝" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMappingQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetMappingQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 映射关系列表 -->
          <el-table height="600" v-loading="mappingLoading" :data="mappingList" border>
            <el-table-column type="selection" width="55" align="center"
              @selection-change="handleMappingSelectionChange" />
            <el-table-column label="码上放心客户名称" align="center" prop="msfxCustomerName" :show-overflow-tooltip="true" />
            <el-table-column label="ERP客户名称" align="center" prop="erpCustomerName" :show-overflow-tooltip="true" />
            <el-table-column label="映射类型" align="center" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.mappingType === 1" type="primary" size="mini">手动映射</el-tag>
                <el-tag v-else type="warning" size="mini">自动匹配</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="审核状态" align="center" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.auditStatus === 0" type="warning" size="mini">待审核</el-tag>
                <el-tag v-else-if="scope.row.auditStatus === 1" type="success" size="mini">已审核</el-tag>
                <el-tag v-else type="danger" size="mini">已拒绝</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
<!--            <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">-->
<!--              <template slot-scope="scope">-->
<!--                <el-button size="mini" type="text" icon="el-icon-view"-->
<!--                  @click="handleMappingView(scope.row)">查看</el-button>-->
<!--                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleMappingEdit(scope.row)"-->
<!--                  v-hasPermi="['basic:customerComparison:edit']">修改</el-button>-->
<!--                <el-button size="mini" type="text" icon="el-icon-check" @click="handleMappingAudit(scope.row)"-->
<!--                  v-hasPermi="['basic:customerComparison:audit']" v-if="scope.row.auditStatus === 0">审核</el-button>-->
<!--                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleMappingDelete(scope.row)"-->
<!--                  v-hasPermi="['basic:customerComparison:remove']">删除</el-button>-->
<!--              </template>-->
<!--            </el-table-column>-->
          </el-table>

          <div class="pagination-container">
            <pagination v-show="mappingTotal > 0" :total="mappingTotal" :page.sync="mappingQueryParams.pageNum"
              :limit.sync="mappingQueryParams.pageSize" @pagination="getMappingList" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建映射对话框 -->
    <el-dialog title="创建映射关系" :visible.sync="mappingDialogVisible" width="600px" append-to-body>
      <el-form ref="mappingForm" :model="mappingForm" :rules="mappingRules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="码上放心客户" prop="msfxCustomerName">
              <el-input v-model="mappingForm.msfxCustomerName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="ERP客户" prop="erpCustomerName">
              <el-input v-model="mappingForm.erpCustomerName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="mappingForm.remark" type="textarea" placeholder="请输入备注信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mappingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitMapping">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 审核映射对话框 -->
    <el-dialog title="审核映射关系" :visible.sync="auditDialogVisible" width="500px" append-to-body>
      <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="审核状态" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input v-model="auditForm.auditRemark" type="textarea" placeholder="请输入审核备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAudit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listMsfxCustomer,
    listErpCustomer,
    listCustomerMapping,
    quickCreateMapping,
    batchCreateMapping,
    auditMapping,
    delCustomerMapping,
    previewAutoMatch,
    executeAutoMatch,
    removeMapping
  } from '@/api/basic/customerComparison'
  import { updateCustomerInfo } from '@/api/wareHouse/billsImport'

  export default {
    name: "CustomerComparison",
    data() {
      return {
        // 当前选项卡
        activeTab: 'comparison',
        // 遮罩层
        msfxLoading: true,
        erpLoading: true,
        mappingLoading: true,
        // 更新往来单位加载状态
        updateCustomerLoading: false,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        msfxTotal: 0,
        erpTotal: 0,
        mappingTotal: 0,
        // 码上放心往来单位表格数据
        msfxCustomerList: [],
        // ERP往来单位表格数据
        erpCustomerList: [],
        // 映射关系表格数据
        mappingList: [],
        // 选中数组
        msfxSelection: [],
        erpSelection: [],
        mappingSelection: [],
        // 查询参数
        queryParams: {
          msfxCustomerName: null,
          erpCustomerName: null,
          mappingStatus: null
        },
        // 码上放心查询参数
        msfxQueryParams: {
          pageNum: 1,
          pageSize: 10,
          customerName: null,
          mappingStatus: null
        },
        // ERP查询参数
        erpQueryParams: {
          pageNum: 1,
          pageSize: 10,
          dwmch: null,
          mappingStatus: null
        },
        // 映射关系查询参数
        mappingQueryParams: {
          pageNum: 1,
          pageSize: 10,
          msfxCustomerName: null,
          erpCustomerName: null,
          auditStatus: null
        },
        // 映射对话框
        mappingDialogVisible: false,
        mappingForm: {
          msfxCustomerId: '',
          msfxCustomerName: '',
          msfxEntId: '',
          erpCustomerCode: '',
          erpCustomerName: '',
          erpDanwbh: '',
          remark: ''
        },
        mappingRules: {
          msfxCustomerName: [{
            required: true,
            message: "码上放心客户不能为空",
            trigger: "blur"
          }],
          erpCustomerName: [{
            required: true,
            message: "ERP客户不能为空",
            trigger: "blur"
          }]
        },
        // 审核对话框
        auditDialogVisible: false,
        auditForm: {
          id: null,
          auditStatus: 1,
          auditRemark: ''
        },
        auditRules: {
          auditStatus: [{
            required: true,
            message: "审核状态不能为空",
            trigger: "change"
          }]
        }
      };
    },
    created() {
      this.getMsfxList();
      this.getErpList();
    },
    methods: {
      /** 选项卡切换 */
      handleTabClick(tab) {
        if (tab.name === 'mapping') {
          this.getMappingList();
        }
      },
      /** 查询码上放心往来单位列表 */
      getMsfxList() {
        this.msfxLoading = true;
        this.msfxQueryParams.mappingStatus = this.queryParams.mappingStatus;
        listMsfxCustomer(this.msfxQueryParams).then(response => {
          this.msfxCustomerList = response.rows;
          this.msfxTotal = response.total;
          this.msfxLoading = false;
        });
      },
      /** 查询ERP往来单位列表 */
      getErpList() {
        this.erpLoading = true;
        this.erpQueryParams.mappingStatus = this.queryParams.mappingStatus;
        listErpCustomer(this.erpQueryParams).then(response => {
          this.erpCustomerList = response.rows;
          this.erpTotal = response.total;
          this.erpLoading = false;
        });
      },
      /** 查询映射关系列表 */
      getMappingList() {
        this.mappingLoading = true;
        listCustomerMapping(this.mappingQueryParams).then(response => {
          this.mappingList = response.rows;
          this.mappingTotal = response.total;
          this.mappingLoading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.msfxQueryParams.pageNum = 1;
        this.erpQueryParams.pageNum = 1;
        this.msfxQueryParams.customerName = this.queryParams.msfxCustomerName;
        this.erpQueryParams.dwmch = this.queryParams.erpCustomerName;
        this.getMsfxList();
        this.getErpList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.msfxQueryParams.customerName = null;
        this.erpQueryParams.dwmch = null;
        this.msfxQueryParams.mappingStatus = null;
        this.erpQueryParams.mappingStatus = null;
        this.handleQuery();
      },
      /** 映射关系搜索 */
      handleMappingQuery() {
        this.mappingQueryParams.pageNum = 1;
        this.getMappingList();
      },
      /** 映射关系重置 */
      resetMappingQuery() {
        this.resetForm("mappingQueryForm");
        this.handleMappingQuery();
      },
      // 多选框选中数据
      handleMsfxSelectionChange(selection) {
        this.msfxSelection = selection;
      },
      // 多选框选中数据
      handleErpSelectionChange(selection) {
        this.erpSelection = selection;
      },
      // 映射关系多选框选中数据
      handleMappingSelectionChange(selection) {
        this.mappingSelection = selection;
      },
      // 获取码上放心行样式
      getMsfxRowClassName({
        row
      }) {
        if (row.isMapped) {
          return 'mapped-row';
        }
        return '';
      },
      // 获取ERP行样式
      getErpRowClassName({
        row
      }) {
        if (row.isMapped) {
          return 'mapped-row';
        }
        return '';
      },
      handleSizeChange(newsize) {
        this.msfxQueryParams.pageNum = 1
        this.msfxQueryParams.pageSize = newsize
        this.getMsfxList()
      },
      handleCurrentChange(newpage) {
        this.msfxQueryParams.pageNum = newpage
        this.getMsfxList()
      },
      handleSizeChangeR(newsize) {
        this.erpQueryParams.pageNum = 1
        this.erpQueryParams.pageSize = newsize
        this.getErpList()
      },
      handleCurrentChangeR(newpage) {
        this.erpQueryParams.pageNum = newpage
        this.getErpList()
      },

      /** 创建映射关系 */
      handleCreateMapping() {
        if (this.msfxSelection.length !== 1 || this.erpSelection.length < 1) {
          this.$modal.msgError("请选择一个码上放心客户和至少一个ERP客户");
          return;
        }

        const msfxCustomer = this.msfxSelection[0];

        // 如果只选择了一个ERP客户，使用单个映射
        if (this.erpSelection.length === 1) {
          const erpCustomer = this.erpSelection[0];
          this.mappingForm = {
            msfxCustomerId: msfxCustomer.customerId,
            msfxCustomerName: msfxCustomer.customerName,
            msfxEntId: msfxCustomer.entId,
            erpCustomerCode: erpCustomer.danwbh,
            erpCustomerName: erpCustomer.dwmch,
            erpDanwbh: erpCustomer.danwbh,
            remark: ''
          };
          this.mappingDialogVisible = true;
        } else {
          // 多个ERP客户，直接批量创建
          this.handleBatchCreateMapping();
        }
      },

      /** 批量创建映射关系 */
      handleBatchCreateMapping() {
        if (this.msfxSelection.length !== 1 || this.erpSelection.length < 2) {
          this.$modal.msgError("请选择一个码上放心客户和至少两个ERP客户");
          return;
        }

        const msfxCustomer = this.msfxSelection[0];
        const erpCustomers = this.erpSelection;

        // 构建批量映射数据
        const batchData = {
          msfxCustomerId: msfxCustomer.customerId,
          msfxCustomerName: msfxCustomer.customerName,
          msfxEntId: msfxCustomer.entId,
          erpCustomerCodes: erpCustomers.map(erp => erp.danwbh),
          erpCustomerNames: erpCustomers.map(erp => erp.dwmch),
          erpDanwbhs: erpCustomers.map(erp => erp.danwbh),
          remark: `批量创建映射关系，共${erpCustomers.length}个ERP客户`
        };

        const erpNames = erpCustomers.map(erp => erp.dwmch).join('、');
        this.$modal.confirm(`确认要为码上放心客户"${msfxCustomer.customerName}"创建与以下${erpCustomers.length}个ERP客户的映射关系吗？\n\n${erpNames}`, "批量创建映射").then(() => {
          batchCreateMapping(batchData).then(response => {
            this.$modal.msgSuccess(response.msg || "批量创建映射关系成功");
            this.getMsfxList();
            this.getErpList();
            if (this.activeTab === 'mapping') {
              this.getMappingList();
            }
          });
        }).catch(() => {
          this.$modal.msgInfo("已取消批量创建");
        });
      },
      /** 提交映射关系 */
      submitMapping() {
        this.$refs["mappingForm"].validate(valid => {
          if (valid) {
            quickCreateMapping(this.mappingForm).then(response => {
              this.$modal.msgSuccess("创建映射关系成功");
              this.mappingDialogVisible = false;
              this.getMsfxList();
              this.getErpList();
              if (this.activeTab === 'mapping') {
                this.getMappingList();
              }
            });
          }
        });
      },
      /** 查看映射关系 */
      handleMappingView(row) {
        // 可以实现查看详情功能
        this.$modal.msgInfo("查看功能待实现");
      },
      /** 修改映射关系 */
      handleMappingEdit(row) {
        // 可以实现编辑功能
        this.$modal.msgInfo("编辑功能待实现");
      },
      /** 审核映射关系 */
      handleMappingAudit(row) {
        this.auditForm = {
          id: row.id,
          auditStatus: 1,
          auditRemark: ''
        };
        this.auditDialogVisible = true;
      },
      /** 提交审核 */
      submitAudit() {
        this.$refs["auditForm"].validate(valid => {
          if (valid) {
            auditMapping(this.auditForm).then(response => {
              this.$modal.msgSuccess("审核成功");
              this.auditDialogVisible = false;
              this.getMappingList();
            });
          }
        });
      },
      /** 删除映射关系 */
      handleMappingDelete(row) {
        const ids = row.id || this.mappingSelection.map(item => item.id);
        this.$modal.confirm('是否确认删除映射关系编号为"' + ids + '"的数据项？').then(function() {
          return delCustomerMapping(ids);
        }).then(() => {
          this.getMappingList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 预览自动匹配 */
      handleAutoMatchPreview() {
        this.$modal.loading("正在分析匹配结果...");
        previewAutoMatch().then(response => {
          this.$modal.closeLoading();
          const data = response.data;

          // 构建预览信息（纯文本格式）
          let message = `自动匹配预览结果：

可匹配数量：${data.successCount} 对
码上放心客户总数：${data.totalMsfxCount}
ERP客户总数：${data.totalErpCount}
码上放心独有：${data.msfxOnlyCount}
ERP独有：${data.erpOnlyCount}

确认要创建这 ${data.successCount} 个映射关系吗？`;

          this.$modal.confirm(message, "自动匹配预览").then(() => {
            this.executeAutoMatch();
          }).catch(() => {
            this.$modal.msgInfo("已取消自动匹配");
          });
        }).catch(error => {
          this.$modal.closeLoading();
          this.$modal.msgError("预览失败：" + (error.msg || "未知错误"));
        });
      },
      /** 执行自动匹配 */
      executeAutoMatch() {
        this.$modal.loading("正在执行自动匹配...");
        executeAutoMatch().then(response => {
          this.$modal.closeLoading();
          const data = response.data;

          this.$modal.msgSuccess(`自动匹配完成！成功创建 ${data.successCount} 个映射关系`);

          // 刷新列表
          this.getMsfxList();
          this.getErpList();
          if (this.activeTab === 'mapping') {
            this.getMappingList();
          }
        }).catch(error => {
          this.$modal.closeLoading();
          this.$modal.msgError("自动匹配失败：" + (error.msg || "未知错误"));
        });
      },
      /** 解除码上放心客户映射 */
      handleRemoveMsfxMapping(row) {
        this.$confirm('确认解除该映射关系吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          removeMapping(row.mappingId).then(response => {
            this.$modal.msgSuccess("解除映射成功");
            this.getMsfxList();
            this.getErpList();
          });
        });
      },
      /** 解除ERP客户映射 */
      handleRemoveErpMapping(row) {
        this.$confirm('确认解除该映射关系吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          removeMapping(row.mappingId).then(response => {
            this.$modal.msgSuccess("解除映射成功");
            this.getMsfxList();
            this.getErpList();
          });
        });
      },
      /** 更新往来单位信息 */
      handleUpdateCustomer() {
        this.$modal.confirm('确认要更新往来单位信息吗？此操作将从外部系统同步最新的往来单位数据。').then(() => {
          this.updateCustomerLoading = true;

          updateCustomerInfo().then(response => {
            this.updateCustomerLoading = false;

            if (response.code === 200) {
              this.$modal.msgSuccess(response.msg || "往来单位信息更新成功");
              // 更新成功后重新加载数据
              this.getMsfxList();
              this.getErpList();
            } else {
              this.$modal.msgError(response.msg || "更新失败");
            }
          }).catch(error => {
            this.updateCustomerLoading = false;

            // 网络错误或其他异常的友好提示
            let errorMessage = "更新往来单位遇到问题，请稍后重试";

            if (error.response) {
              if (error.response.status === 500) {
                errorMessage = "服务器内部错误，请联系管理员";
              } else if (error.response.status === 404) {
                errorMessage = "请求的接口不存在，请联系管理员";
              } else if (error.response.status === 403) {
                errorMessage = "没有权限执行此操作";
              } else {
                errorMessage = `请求失败 (${error.response.status})，请重试`;
              }
            } else if (error.request) {
              errorMessage = "网络连接失败，请检查网络后重试";
            } else {
              errorMessage = error.message || "未知错误，请重试";
            }

            this.$modal.msgError(errorMessage);
          });
        }).catch(() => {
          this.$modal.msgInfo("已取消更新");
        });
      }
    }
  };
</script>

<style scoped lang="scss">
 .comparison-container {
   display: flex;
   gap: 20px;
   height: calc(100vh - 240px);
 }

 .left-panel,
 .right-panel {
   flex: 1;
   width: 50%;
   min-width: 600px;
   border-radius: 4px;
   display: flex;
   flex-direction: column;
 }

 .panel-header {
   background-color: #f5f7fa;
   padding: 15px 20px;
   border-bottom: 1px solid #e4e7ed;
   display: flex;
   justify-content: space-between;
   align-items: center;
   min-height: 60px;
   box-sizing: border-box;
 }

 .el-table {
   border-top: none;
   min-width: 580px;
   flex: 1;
 }

 .pagination-container {
   padding: 10px;
   background-color: #fff;
   text-align: right;
   height: 35px !important;
 }
  .mapping-management {
    padding: 20px;
  }

  /* 已映射行样式 */
  .el-table .mapped-row {
    background-color: #f0f9ff;
  }

  /* 统一表格行高度 */
  .el-table .el-table__row {
    height: 50px;
  }

  .el-table .el-table__row td {
    height: 50px;
    vertical-align: middle;
  }

  /* 统一标签样式 */
  .el-tag {
    height: 24px;
    line-height: 22px;
    vertical-align: middle;
  }

  .el-table .mapped-row:hover>td {
    background-color: #e6f7ff !important;
  }

  /* 选项卡样式调整 */
  .el-tabs {
    margin-top: -10px;
  }

  .el-tabs__content {
    padding: 20px 0;
  }

  /* 对话框样式 */
  .dialog-footer {
    text-align: right;
  }

  /* 状态标签样式 */
  .el-tag {
    margin-right: 5px;
  }
</style>
